package com.msb.mall.product.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.constant.ProductConstant;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;
import com.msb.mall.product.dao.AttrDao;
import com.msb.mall.product.entity.AttrAttrgroupRelationEntity;
import com.msb.mall.product.entity.AttrEntity;
import com.msb.mall.product.entity.AttrGroupEntity;
import com.msb.mall.product.entity.CategoryEntity;
import com.msb.mall.product.service.AttrAttrgroupRelationService;
import com.msb.mall.product.service.AttrGroupService;
import com.msb.mall.product.service.AttrService;
import com.msb.mall.product.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId, String attrtype) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type", "base".equalsIgnoreCase(attrtype)?1:0);
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(obj -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        records.forEach(item -> {
            Long catelogIds = item.getCatelogId();
            List<Long> paths = new ArrayList<>();
            List<Long> parentPath = this.findParentPath(catelogIds, paths);
            Collections.reverse(parentPath);
            StringBuilder stringBuilder = new StringBuilder();
            int size = parentPath.size();
            for (int i = 0; i < size; i++) {
                Long l = parentPath.get(i);
                String name = categoryService.getById(l).getName();
                stringBuilder.append(name);
                if (i < size - 1) { // 如果不是最后一个元素
                    stringBuilder.append(" / ");
                }
            }
            item.setCatelogName(stringBuilder.toString());
        });
        pageUtils.setList(records);
        return pageUtils;
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        paths.add(catelogId);
        CategoryEntity entity = categoryService.getById(catelogId);
        if(entity.getParentCid() != 0){
            findParentPath(entity.getParentCid(),paths);
        }
        return paths;
    }

    @Override
    public PageUtils getNoAttrRelation(Long attrGroupId, Map<String, Object> params) {
        Long catelogId = attrGroupService.getById(attrGroupId).getCatelogId();
        List<AttrGroupEntity> list = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        if (list != null && !list.isEmpty()) {
            List<Long> groupIds = list.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
            List<Long> attrIds = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds)).stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

            QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("catelog_id", catelogId)
                    .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE);

            if (!attrIds.isEmpty()) {
                wrapper.notIn("attr_id", attrIds);
            }

            String key = (String) params.get("key");
            if (!StringUtils.isEmpty(key)) {
                wrapper.and(obj -> {
                    obj.eq("attr_id", key).or().like("attr_name", key);
                });
            }
            // 查询对应的相关信息
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    wrapper
            );
            return new PageUtils(page);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );
        page.getRecords().forEach(item -> {
            Long catelogIds = item.getCatelogId();
            List<Long> paths = new ArrayList<>();
            List<Long> parentPath = this.findParentPath(catelogIds, paths);
            Collections.reverse(parentPath);
            StringBuilder stringBuilder = new StringBuilder();
            int size = parentPath.size();
            for (int i = 0; i < size; i++) {
                Long l = parentPath.get(i);
                String name = categoryService.getById(l).getName();
                stringBuilder.append(name);
                if (i < size - 1) { // 如果不是最后一个元素
                    stringBuilder.append(" / ");
                }
            }
            item.setCatelogName(stringBuilder.toString());
        });
        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void saveDetails(AttrEntity attr) {
        this.save(attr);
        AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
        BeanUtils.copyProperties(attr, attrAttrgroupRelation);
        attrAttrgroupRelationService.save(attrAttrgroupRelation);
    }

    @Override
    public void updateDetails(AttrEntity attr) {
        this.updateById(attr);
        AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
        BeanUtils.copyProperties(attr, attrAttrgroupRelation);
        AttrAttrgroupRelationEntity one = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrAttrgroupRelation.getAttrId()).eq("attr_group_id", attrAttrgroupRelation.getAttrGroupId()));
        if (one != null) {
            attrAttrgroupRelationService.updateById(attrAttrgroupRelation);
        }else {
            attrAttrgroupRelationService.save(attrAttrgroupRelation);
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("catelog_id", catelogId).eq("attr_type", 1);
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

}